//
//  JPillnessDetailController.m
//  JPKY
//
//  Created by Vitas on 2016/11/16.
//  Copyright © 2016年 Vitas. All rights reserved.
//

#import "JPillnessDetailController.h"
#import "InterfaceTool.h"
#import <MJRefresh.h>
#import "SVProgressHUD.h"
#import "YYModel.h"
#import "JPillnessModel.h"

static NSString *reusedIllnessDetailCell = @"reusedIllnessDetailCell";

@interface JPillnessDetailController () <UITableViewDelegate,UITableViewDataSource>

/**
 *  tableView
 */
@property (nonatomic, strong) UITableView *tableView;

/**
 *  搜索框
 */
@property (nonatomic, strong) UITextField *seachBar;

/**
 *  疾病模型数组
 */
@property (nonatomic, strong) NSMutableArray *illnessArray;

/**
 *  请求数据index
 */
@property (nonatomic, assign) int pageIndex;

/**
 *  请求最大数
 */
@property (nonatomic,assign ) NSInteger maxPageIndex;

@property (nonatomic, assign) NSInteger lastId;

@end

@implementation JPillnessDetailController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
    [SVProgressHUD show];
    
    // 请求最大数
    self.maxPageIndex = 50;
    
    // 初始化请求数
    self.pageIndex = 1;
    
    // 设置导航栏
    [self setNavgationBar];
    
    [self.view addSubview:self.tableView];
    
    // 设置上下拉刷新
    [self setupMJRefresh];
}

/**
 *  设置navgationBar
 */
- (void)setNavgationBar {
    UIButton *button = [[UIButton alloc] init];
    button.frame = CGRectMake(0, 0, 50, 40);
    [button setImage:[UIImage imageNamed:@"home_nav_button_back"] forState:UIControlStateNormal];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [button addTarget:self action:@selector(didBackButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    self.navigationItem.titleView = self.seachBar;
    
    UIButton *rightButton= [[UIButton alloc] init];
    rightButton.frame = CGRectMake(0, 0, 50, 40);
    [rightButton setTitle:@"搜索" forState:UIControlStateNormal];
    
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = searchItem;
}

/**
 *  设置上下拉刷新
 */
- (void)setupMJRefresh {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getMoreIllnessModel)];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [footer setTitle:@"数据加载完毕" forState:MJRefreshStateNoMoreData];
    self.tableView.mj_footer = footer;
    [self.tableView.mj_footer beginRefreshing];
}

/**
 *  上拉加载数据
 */
- (void)loadData {
    if (self.maxPageIndex <= self.pageIndex) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        return;
    }
    
    InterfaceTool *tool = [InterfaceTool sharedInterfaceTool];
    [tool getSubsectionWithDisease:self.illnessIndex Page:self.pageIndex success:^(id response) {
        //请求数据错误
        if ([response isKindOfClass:[NSError class]]) {
            
            NSLog(@"error = %@",response);
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
            delay(1);
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        
        //获取数据成功
        if (![response[@"msg"] isEqualToString:@"FAIL"]) {
            
            //返回数据为空时
            if ([response[@"data"] isEqual:[NSNull null]]) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                self.maxPageIndex = self.pageIndex;
                MJRefreshAutoNormalFooter *footer = (MJRefreshAutoNormalFooter *)self.tableView.mj_footer;
                [footer setTitle:@"数据加载完毕" forState:MJRefreshStateNoMoreData];
                return;
            }
            
            //处理返回的数据
            NSArray *dataArr = response[@"data"];
            for (NSDictionary* dict in dataArr) {
                JPillnessModel *model = [JPillnessModel yy_modelWithDictionary: dict];
                if (model.ci3_id > self.lastId) {
                    [self.illnessArray addObject:model];
                    self.lastId = model.ci3_id;
                }
            }
            [self.tableView.mj_footer endRefreshing];
            self.pageIndex = self.pageIndex +1;
            
            [SVProgressHUD showSuccessWithStatus:@"加载成功"];
            delay(1);
            
            [self.tableView reloadData];
        } else {
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

/**
 *  下拉刷新获取数据
 */
- (void)getMoreIllnessModel {
    
    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
}

#pragma mark - UITableViewdelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.illnessArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reusedIllnessDetailCell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reusedIllnessDetailCell"];
    }

    cell.textLabel.attributedText = nil;
    JPillnessModel *model =  self.illnessArray[indexPath.row];
    cell.textLabel.text = model.ci3_name;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *chooseString;

    JPillnessModel *model = self.illnessArray[indexPath.row];
    chooseString = model.ci3_name;
    
    if (self.getIllnessString) {
        self.getIllnessString(chooseString,indexPath.row);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  返回按钮触发事件
 */
- (void)didBackButton:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 懒加载

- (NSMutableArray *)illnessArray {
    
    if (!_illnessArray) {
        _illnessArray = [NSMutableArray array];
    }
    return _illnessArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    
    return _tableView;
}

- (UITextField *)seachBar {
    if (!_seachBar) {
        _seachBar = [[UITextField alloc] init];
        _seachBar.borderStyle = UITextBorderStyleRoundedRect;
        _seachBar.backgroundColor = [UIColor whiteColor];
        _seachBar.frame = CGRectMake(0, 0, 200, 20);
        _seachBar.placeholder = @"  🔍 疾病细分搜索 ";
    }
    
    return _seachBar;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
